package ru.gosoplata.model 
{
	import ru.gosoplata.model.vo.Commission;
	/**
	 * ...
	 * @author 
	 */
	public class Provider 
	{
		private var _useChange:Boolean
		private var _providerXML:XML;
		private var _commissionXml:XML;
		private var _childs:XMLList;
		
		public function Provider() 
		{
		}
		//TODO: не используется
		//private var _fullName:String="";
		//public function get fullName():String 
		//{
			//return _fullName;
		//}
		
		public function get folder():String 
		{
			return _providerXML?_providerXML.@folder:"all";
		}
		
		public function set id(value:String):void 
		{
			var finded:XMLList = TmpModel.config.req.providers.row.(@id == value);
		
			//_fullName = "";
			_providerXML = null;
			_commissionXml = null;
			_useChange = false;
			
			_childs = null;
			
			if (finded.length())
			{
				_providerXML = finded[0];
				_childs = TmpModel.config.req.providers.row.(@parent_id == id);
				if (_providerXML.@prv_id != "0" && !isFolder)//TODO: жалко что ли - пусть работает /
				{
					_commissionXml = TmpModel.config.providers.provider.(@id == _providerXML.@prv_id)[0];
					//_fullName = commissionXml.@full_name.toString();
					_useChange = _commissionXml.hasOwnProperty('@use_change') && _commissionXml.@use_change == "1";
					TmpModel.debugOutput.add("_commissionXml "+_commissionXml.commission +' '+_commissionXml)
					if (_commissionXml.commission.hasOwnProperty('@profile')) {
						_commissionXml = TmpModel.config.commission_profiles.profiles.profile.(@id == _commissionXml.commission.@profile)[0];
						TmpModel.debugOutput.add("@profile "+_commissionXml)
					}else {
						_commissionXml =new XML('<profile><profile-data from-amount="0" to-amount="'+TmpModel.MAX_SUM_TERM+'" com-percent="'+_commissionXml.commission+'"/></profile>');
					}
				}
				TmpModel.debugOutput.add("Provider id " + id + " parrent " + _providerXML.@parent_id+ " length "+_providerXML.@length+" regexp "+_providerXML.@regex);
				
			}else
			{
				TmpModel.debugOutput.add("Provider id " + id + " не найден.");
				id = "all";
			}
		}
		
		public function get id():String 
		{
			if (_providerXML)
			{
				return _providerXML.@id
			}
			return "all";
		}
		
		public function get providerID():String 
		{
			if (_providerXML)
			{
				return _providerXML.@prv_id;
			}
			return "0";
		}
		
		public function get isFolder():Boolean 
		{
			return (_providerXML && _providerXML.@is_folder == "0")?false:true;
		}
		
		public function get image():String
		{
			return getImagePath(_providerXML);
		}
		
		public function get fixPrice():uint 
		{
			return _providerXML?_providerXML.@fixPrice:0;
		}
		
		public function get useChange():Boolean 
		{
			return _useChange;
		}
		
		//TODO: должно стать атовизмом + getImagePath
		public function get providerXML():XML 
		{
			return _providerXML;
		}
		
		//TODO: должно стать атовизмом
		public function get nextPage():String 
		{
			return _providerXML?_providerXML.@next_page:"";
		}
		
		public function get inputFilds():String 
		{
			//TODO: хорошо бы эти данные приходили с конфигом...
			var nextPage:String = _providerXML?_providerXML.@next_page:"";
			
			
			
			if (nextPage == "p_universal_kb.html")
			{
				//fields_count = 1;
				//keypad.visible = false;
				//keyboard.visible = true;
				//keyboard.reDrawKeyBoard();
				//up_txt_str = "Введите номер \nдоговора/лицевого счета";
				//inputtxt1.y = 355;
				//testplane.y = 340;
				//prv_logo.y = 200;
				//up_txt.y = txt_y - 20 - 180;
			}
			
			return null;
		}
		
		//TODO: почему картики от cellular в other?
		//TODO: переделать получение картинки провайдера
		static public function getImagePath(provider:XML):String 
		{
			if (!provider) return "";
			
			var folder:String = "/logo/" + provider.@folder +"/";
			if (provider.@folder == "cellular") folder = "/sotovie_operatori/logo/";
			return TmpModel.IMG_FOLDER + folder + provider.@image;
		}
		
		public function parentId():String 
		{
			return (_providerXML)?_providerXML.@parent_id:"all";
		}
		//TODO: сделать как и выбор группы + урезание детей
		public function serch(str:String,inFolder:Boolean=false):void 
		{
			//_fullName = "";
			_providerXML = null;
			_commissionXml = null;
			_useChange = false;
			
			var finded:XMLList = TmpModel.config.req.providers.row;
			if(inFolder)finded=TmpModel.config.req.providers.row.(@folder == folder)
			_childs=finded.(@name.toLowerCase().indexOf(str.toLowerCase()) !=-1);
		}
		
		public function getChilds():XMLList 
		{
			return _childs;
		}
		
		public function getCommission(sum:Number):Commission 
		{
			var val:Number = 0;
			var toString:String = "0 руб.";
			for each (var range:XML in _commissionXml.children()) 
			{
				TmpModel.debugOutput.add("Commission range " + range.toXMLString());
				if (sum<Number(range.attribute("to-amount")))
				{
					if (range.hasOwnProperty("@com-percent")) 
					{
						val = Number(range.attribute("com-percent"));
						toString = val+" %";
						val = sum / 100 * val;
					}else {
						val = Number(range.attribute("com-min"));
						toString = val+" руб.";
					}
					TmpModel.debugOutput.add("Commission find " + toString);
					break;
				}
			}
			
			return new Commission(val,toString);
		}
		
		public function validateAccount(value:String):Boolean 
		{
			if (!isFolder && _providerXML!=null && value.search(RegExp(_providerXML.@regex)) == 0)//TODO: length задается в regex и у некоторых ее нет //&& value.length == _providerXML.@length
			{
				return true;
			}
			return false;
		}
	}
}